import React, {useState, useMemo, useCallback} from 'react';
import {Modal} from '@/components/modals/Modal';
import {SpaceIcon} from '@/components/ui/SpaceIcon';
import {useToast} from '@/hooks/ui';
import {useSpaces, useAttachCollectionToSpace} from '@/hooks/api';
import {cn} from '@/lib/utils';
import type {SpaceCollection} from '@/types';
import {ScrollContainer} from '@/components/ui/ScrollContainer';

interface MoveCollectionModalProps {
    collection: SpaceCollection;
    isOpen: boolean;
    onClose: () => void;
}

export const MoveCollectionModal: React.FC<MoveCollectionModalProps> = ({
    collection,
    isOpen,
    onClose
}) => {
    const [selectedSpaceId, setSelectedSpaceId] = useState<number | null>(null);

    const toast = useToast();

    // 使用 TanStack Query hooks
    const { data: spacesData } = useSpaces();
    const attachMutation = useAttachCollectionToSpace();

    // 排序后的空间列表（按 position 降序）
    const spaces = useMemo(() => {
        if (!spacesData) return [];
        return [...spacesData].sort((a, b) => b.position - a.position);
    }, [spacesData]);

    const availableSpaces = useMemo(() => {
        return spaces.filter(space => space.id !== collection.spaceId);
    }, [spaces, collection.spaceId]);

    const handleMove = useCallback(async () => {
        if (!selectedSpaceId) return;

        try {
            // 调用 TanStack Query mutation
            await attachMutation.mutateAsync({
                spaceId: selectedSpaceId,
                data: {
                    collection_id: collection.collectionId,
                    target_space_id: selectedSpaceId,
                }
            });

            const targetSpace = spaces.find(s => s.id === selectedSpaceId);
            toast.success(`集合已移动到 "${targetSpace?.name || '未知空间'}"`);
            onClose();
        } catch (error) {
            console.error('移动集合失败:', error);
            toast.error('移动失败，请重试');
        }
    }, [selectedSpaceId, attachMutation, collection.collectionId, spaces, toast, onClose]);

    return (
        <Modal
            open={isOpen}
            onClose={onClose}
            title="移动集合"
            size="md"
            className="max-w-md"
            bodyScrollable={true}
            footer={(
                <div className="flex items-center justify-between">
                    {/* 说明：左侧提示 */}
                    <div className="flex items-center gap-2 text-xs text-gray-500 min-w-0">
                        <div className="w-1 h-1 bg-blue-500 rounded-full"></div>
                        <span className="truncate">移动后将在目标空间显示</span>
                    </div>
                    {/* 说明：右侧按钮 */}
                    <div className="flex items-center gap-3 flex-shrink-0">
                        <button
                            type="button"
                            onClick={onClose}
                            className="btn-secondary"
                            disabled={attachMutation.isPending}
                        >
                            取消
                        </button>
                        <button
                            type="button"
                            onClick={handleMove}
                            disabled={attachMutation.isPending || !selectedSpaceId}
                            className="btn-primary"
                        >
                            {attachMutation.isPending ? '移动中...' : '移动'}
                        </button>
                    </div>
                </div>
            )}
        >
            {/* 说明：上 auto / 下 1fr；外层滚动已经由 Modal 内部的 ScrollContainer 托管 */}
            <div className="grid grid-rows-[auto_minmax(0,1fr)] gap-6">
                {/* 顶部信息（固定） */}
                <div className="p-4 bg-gray-100 rounded-lg">
                    <h3 className="font-medium text-gray-900 mb-1">
                        <span className="truncate">{collection.collection.name}</span>
                    </h3>
                    <p className="text-sm text-gray-600">
                        <span className="truncate">包含 {collection.tabs.length} 个标签页</span>
                    </p>
                </div>

                {/* 说明：内层“卡片”区域：头固定 + 主体滚动（关键：给这块上限） */}
                <fieldset className="min-h-0">
                    <div
                        className="grid grid-rows-[auto_minmax(0,1fr)] overflow-hidden min-h-[180px] h-[38dvh] max-h-[350px]"
                    >
                        {/* 标题（固定） */}
                        <legend id="target-space-legend" className="text-sm font-medium text-gray-700 mb-3">
                            选择目标空间
                        </legend>

                        {/* 列表承重位（允许压缩） */}
                        <div className="min-h-0">
                            {/* 说明：真正滚动的内层；现在 h-full 有了明确参照（上面的 maxHeight） */}
                            <ScrollContainer
                                className="h-full"
                                padRightForScrollbar={false}
                                overscrollBehavior="contain"
                            >
                                <div className="space-y-3 pr-2">
                                    {availableSpaces.length === 0 ? (
                                        <p className="text-sm text-gray-500 text-center py-4">没有可用的目标空间</p>
                                    ) : (
                                        availableSpaces.map((space) => (
                                            <label
                                                key={space.id}
                                                className={cn(
                                                    'flex items-center gap-3 p-3 border rounded-lg cursor-pointer',
                                                    'hover:bg-gray-50 transition-colors',
                                                    selectedSpaceId === space.id ? 'border-primary-500 bg-primary-50' : 'border-gray-200'
                                                )}
                                            >
                                                {/* 说明：使用原生 radio，保留可访问性 */}
                                                <input
                                                    id={`space-${space.id}`}
                                                    type="radio"
                                                    name="targetSpace"
                                                    value={space.id}
                                                    checked={selectedSpaceId === space.id}
                                                    onChange={() => setSelectedSpaceId(space.id)}
                                                    className="sr-only"
                                                />
                                                <SpaceIcon
                                                    iconId={space.icon}
                                                    size={17}
                                                    color={space.icon_color}
                                                    className="flex-shrink-0"
                                                />
                                                <div className="flex-1 min-w-0">
                                                    <div className="text-base text-gray-500">{space.name}</div>
                                                </div>
                                                {selectedSpaceId === space.id && (
                                                    <div className="w-5 h-5 rounded-full bg-primary-500 flex items-center justify-center flex-shrink-0">
                                                        <div className="w-2 h-2 bg-white rounded-full" />
                                                    </div>
                                                )}
                                            </label>
                                        ))
                                    )}
                                </div>
                            </ScrollContainer>
                        </div>
                    </div>
                </fieldset>
            </div>
        </Modal>
    );
};
